package contoller

import (
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"mall-app/internal/dto"
	"mall-app/internal/service"
	"net/http"
)

type loginCtl struct{}

// 系统登录
func (c *loginCtl) Login(ctx *gin.Context) {
	if ctx.Request.Method != "POST" {
		ctx.JSON(http.StatusOK, gin.H{"msg": "仅支持POST请求", "code": -1})
	}
	var req *dto.LoginReq
	if err := ctx.ShouldBind(&req); err != nil {
		ctx.JSON(http.StatusOK, gin.H{"msg": "登录错误", "code": -1})
		return
	}
	// 校验验证码
	verifyRes := base64Captcha.VerifyCaptcha(req.IdKey, req.Captcha)
	if !verifyRes {
		ctx.JSON(http.StatusOK, gin.H{"msg": "验证码不正确", "code": -1})
		return
	}
	// 系统登录
	if token, err := service.UserLogin(req.UserName, req.Password, ctx); err != nil {
		ctx.JSON(http.StatusOK, common.JsonResult{
			Code: -1,
			Msg:  err.Error(),
		})
		return
	} else {
		ctx.JSON(http.StatusOK, common.JsonResult{
			Code: 0,
			Msg:  "登录成功",
			Data: gin.H{
				"access_token": token,
			},
		})
	}

}

func (c *loginCtl) Logout(ctx *gin.Context) {

}

// 验证码
func (c *loginCtl) Captcha(ctx *gin.Context) {
	// 验证码参数配置：字符,公式,验证码配置
	var configC = base64Captcha.ConfigCharacter{
		Height: 60,
		Width:  240,
		//const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,CaptchaModeNumberAlphabet:数字字母混合.
		Mode:               base64Captcha.CaptchaModeAlphabet,
		ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
		ComplexOfNoiseDot:  base64Captcha.CaptchaComplexLower,
		IsShowHollowLine:   false,
		IsShowNoiseDot:     false,
		IsShowNoiseText:    false,
		IsShowSlimeLine:    false,
		IsShowSineLine:     false,
		CaptchaLen:         6,
	}
	//create a characters captcha.
	idKeyC, capC := base64Captcha.GenerateCaptcha("", configC)
	//以base64编码
	base64stringC := base64Captcha.CaptchaWriteToBase64Encoding(capC)
	ctx.JSON(http.StatusOK, gin.H{"msg": "操作成功", "code": 0, "data": base64stringC, "idKey": idKeyC})
}
